/*
 * this is an example from libevent on the net.
 * change to an echo server!
 *
 */
#include <netinet/in.h>
#include <sys/socket.h>
#include <fcntl.h>

#include <event2/event.h>
#include <event2/buffer.h>
#include <event2/bufferevent.h>

#include <assert.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <string>


#define MAX_LINE 16384

void read_cb(struct bufferevent *bev, void *ctx)
{
    printf("read cb, new data.. arrive.....\n");
    struct evbuffer *input, *output;
    input = bufferevent_get_input(bev);
    output = bufferevent_get_output(bev);

    char *line;
    size_t n;
    int i;

    while ((line = evbuffer_readln(input, &n, EVBUFFER_EOL_LF))) {
		std::string val = line;
		if (val == "aaa") {
			sleep(4);
			evbuffer_add(output, line, n);
			evbuffer_add(output, "\n", 1);
		}
        free(line);
    }

    if (evbuffer_get_length(input) >=MAX_LINE) {
        // too long
        char buf[1024];
        while (evbuffer_get_length(input)) {
            int n = evbuffer_remove(input, buf, sizeof(buf));
            evbuffer_add(output, buf, n);
        }
        evbuffer_add(output, "\n", 1);
    }
}

void error_cb(struct bufferevent *bev, short error, void *ctx)
{
    if (error & BEV_EVENT_EOF) {
        // connection has been closed, do any clean up here
        printf("remote socekt closed!\n");
    } else if (error & BEV_EVENT_ERROR) {
        // check errno to see what error occured
        printf("get an errer(%d)!\n", error);
    } else if (error & BEV_EVENT_TIMEOUT) {
        // must be a timeout event handle, handle it
        printf("time out event happen!\n");
    }
    bufferevent_free(bev);
    printf("a bev(connection) freed!!!\n");
    
}

void on_accept(evutil_socket_t listener, short event, void *arg)
{
    printf("new fd accept....\n");
    struct event_base* base = (event_base*)arg;
    struct sockaddr_in ss;
    socklen_t slen = sizeof(ss);
    int fd = accept(listener, (struct sockaddr*)&ss, &slen);
    if (fd < 0) {
        perror("accept");
    } else if (fd > FD_SETSIZE) {
        perror("fb > FD_SETSIZE");
        close(fd);
    }else {
        evutil_make_socket_nonblocking(fd);
        struct bufferevent *bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE);
        bufferevent_setcb(bev, read_cb, NULL, error_cb, NULL);
        bufferevent_enable(bev, EV_READ|EV_WRITE);
    }
}

void on_timer(evutil_socket_t fd, short events, void *ctx)
{
	printf("timer tick a second ...\n");
}

void run()
{
    evutil_socket_t listener;
    struct sockaddr_in sin;
    struct event_base *base;
    struct event *listener_event;

    base = event_base_new();
    if (!base) return;

    bzero(&sin, sizeof(sin));
    sin.sin_family = AF_INET;
    sin.sin_addr.s_addr = 0;
    sin.sin_port = htons(12345);

    listener = socket(AF_INET, SOCK_STREAM, 0);
    if (listener < 0) return;
    evutil_make_socket_nonblocking(listener);

#ifndef WIN32
    {
        int one = 1;
        setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
    }
#endif

    if (bind(listener, (struct sockaddr*)&sin, sizeof(sin)) < 0) {
        perror("bind");
        return;
    }

    if (listen(listener, 16)<0) {
        perror("listen");
        return;
    }

    listener_event = event_new(base, listener, EV_READ|EV_PERSIST, on_accept, (void*)base);
    event_add(listener_event, NULL);

	struct event *timer_event = event_new(base, -1, EV_PERSIST, on_timer, (void*)base);
	struct timeval interval = {1000, 50000};
	evtimer_add(timer_event, &interval);

    printf("echo server run ....\n");
    event_base_dispatch(base);
}

int main(int argc, char **argv)
{
    setvbuf(stdout, NULL, _IONBF, 0);

    run();
    return 0;
}


